//
//  GQJNotificationViewController160822.m
//  TotalDemo
//
//  Created by gujian on 16/8/22.
//  Copyright © 2016年 gujian. All rights reserved.
//

#import "GQJNotificationViewController160822.h"
#import "GQJCategoryViewController.h"

static NSString *kGQJNotificaiton = @"kGQJNotification";
const char * GQJNotiContext = "GQJNotiContext";

@interface GQJNotificationViewController160822 ()

@property (nonatomic, strong) id localObserver;
@property (nonatomic, strong) UIView *subView;

@end

@implementation GQJNotificationViewController160822

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"Notificaiton初探";

    NSNotificationCenter *defaultCenter = [NSNotificationCenter defaultCenter];
    
    
    //add observer
    [defaultCenter addObserver:self selector:@selector(handleNotification:) name:kGQJNotificaiton object:nil];
    NSOperationQueue *mainQueue = [NSOperationQueue mainQueue];
    
    // The return value is retained by the system, and should be held onto by the caller in
    // order to remove the observer with removeObserver: later, to stop observation.
    _localObserver = [defaultCenter addObserverForName:kGQJNotificaiton object:nil queue:mainQueue usingBlock:^(NSNotification * _Nonnull note) {
        LotLog(@"1currentThread%@-noti:%@",[NSThread currentThread],note);
    }];
    

    //KVO
    _subView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 100, 100)];
    [self addObserver:self forKeyPath:@"subView" options:NSKeyValueObservingOptionNew context:&GQJNotiContext];
//    self.subView.backgroundColor = [UIColor redColor];
    self.subView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 100, 120)];
    
    LotLog(@"viewDidLoad end");
    
    
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context
{
    if ([keyPath isEqualToString:@"subView"]) {
        LotLog(@"the keyPath:%@",keyPath);
    }
}


- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    
    sleep(2.0);
    
    [[NSNotificationCenter defaultCenter] postNotificationName:kGQJNotificaiton object:nil];
    
    NSLog(@"handle method compelte");
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:_localObserver];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [self removeObserver:self forKeyPath:@"subView"];
}


/**
 *  探索通知同步异步问题
 *
 *  @param noti 接到的notification
 */
- (void)handleNotification:(NSNotification *)noti
{
    
    LotLog(@"2currentThread%@-noti:%@", [NSThread currentThread], noti);
}

@end
